import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_value_notifier.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/widgets/ex_value_builder.dart';
import 'package:xws/widgets/hold_btn.dart';

/// 设置数量
class SetCount extends StatefulWidget {
  const SetCount({Key? key, this.init, this.onChanged}) : super(key: key);

  @override
  _SetCountState createState() => _SetCountState();

  final int? init;
  final Function(int)? onChanged;
}

class _SetCountState extends State<SetCount> {
  late SafeValueNotifier<int> _count;

  @override
  void initState() {
    super.initState();
    _count = SafeValueNotifier<int>(widget.init ?? 1);
    widget.onChanged?.call(1);
  }

  @override
  void dispose() {
    _count.dispose();
    super.dispose();
  }

  void _change({bool isAdd = false}) {
    if (isAdd) {
      if (_count.value < 999) _count.value++;
      widget.onChanged?.call(_count.value);
    } else {
      if (_count.value > 1) _count.value--;
      widget.onChanged?.call(_count.value);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      width: 130,
      child: Row(
        children: <Widget>[
          _buildBtn(),
          Expanded(child: _input),
          _buildBtn(isAdd: true),
        ],
      ),
    );
  }

  Widget get _input {
    return Container(
      alignment: Alignment.center,
      color: theme(context).withOpacity(0.1),
      child: ExValueBuilder<int>(
        valueListenable: _count,
        builder: (_, int c, __) {
          return Text(c.toString(), style: TextStyle(color: theme(context)));
        },
      ),
    );
  }

  Widget _buildBtn({bool isAdd = false}) {
    return HoldBtn(
      onTap: () => _change(isAdd: isAdd),
      onHold: () => _change(isAdd: isAdd),
      alignment: Alignment.center,
      width: 40,
      color: theme(context),
      child: Icon(
        isAdd ? Icons.add_rounded : Icons.remove_rounded,
        size: 20,
        color: white(context),
      ),
      padding: EdgeInsets.zero,
      borderRadius: isAdd
          ? const BorderRadius.horizontal(right: Radius.circular(4))
          : const BorderRadius.horizontal(left: Radius.circular(4)),
    );
  }
}
